package com.hinotoyk.testsystem.uitls;

import java.util.*;

public class QueryMap {

    private Map<String, List<String>> params;

    public String getParameter(String key){
        List<String> list = params.get(key);
        if(list != null && list.size() > 0)
            return list.get(0);

        return null;
    }

    public List<String> getParameterValues(String key){
        List<String> list = params.get(key);
        if(list != null && list.size() > 0)
            return list;

        return null;
    }

    public String getParameterValuesString(String key){
        List<String> list = getParameterValues(key);
        if(list != null) {
            String str = new String();

            for(int i = 0; i < list.size(); ++i)
                str += list.get(i);

            return str;
        }

        return null;
    }

    public static QueryMap parse(String url) {
        QueryMap map = new QueryMap();
        
        if (url == null) {
            return map;
        }
        url = url.trim();
        if (url.equals("")) {
            return map;
        }

        //有参数
        String[] params = url.split("&");
        map.params = new HashMap<>();
        for (String param : params) {
            String[] keyValue = param.split("=");

            List<String> list = map.params.get(keyValue[0]);
            if(list != null){
                list.add(keyValue[1]);
            }else {
                list = new ArrayList<>();
                list.add(keyValue[1]);
                map.params.put(keyValue[0], list);
            }
        }

        return map;
    }

    @Override
    public String toString() {
        return "QueryMap{" +
                "params=" + params +
                '}';
    }
}
